<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>历史环境数据图表</title>
    <script src="../static/echarts.min.js"></script>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 2rem;
            background-color: #f4f6f9;
        }

        h1 {
            text-align: center;
            color: #333;
        }

        .chart-container, .table-container {
            display: flex;
            flex-direction: column;
            gap: 2rem;
            margin-top: 2rem;
        }

        .chart, .table {
            background-color: white;
            padding: 1.5rem;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .chart {
            height: 400px;
        }

        @media (max-width: 768px) {
            .chart {
                height: 300px;
            }
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 1rem;
        }

        th, td {
            padding: 0.75rem;
            border-bottom: 1px solid #ddd;
            text-align: center;
        }

        th {
            background-color: #f0f0f0;
        }

        .toggle-btn {
            display: block;
            margin: 1rem auto;
            padding: 0.5rem 1rem;
            background-color: #0d6efd;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 1rem;
        }

        .toggle-btn:hover {
            background-color: #0b5ed7;
        }
    </style>
</head>
<body>

<div id="navbar"></div>

<script>
fetch('/static/nav.html')
    .then(response => response.text())
    .then(data => {
        document.getElementById('navbar').innerHTML = data;
    })
    .catch(err => console.error('无法加载导航栏:', err));
</script>

<h1>历史温湿度与光照数据</h1>

<!-- 切换按钮 -->
<button class="toggle-btn" onclick="toggleView()">切换：图表 / 表格</button>

<!-- 图表容器 -->
<div id="chart-view" class="chart-container">
    <div id="tempChart" class="chart"></div>
    <div id="humChart" class="chart"></div>
    <div id="lightChart" class="chart"></div>
</div>

<!-- 表格容器 -->
<div id="table-view" class="table-container" style="display: none;">
    <div class="table">
        <table id="data-table">
            <thead>
                <tr>
                    <th>时间</th>
                    <th>温度 (°C)</th>
                    <th>湿度 (%)</th>
                    <th>光照强度 (lux)</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>
</div>

<script>
let chartData = null;

// 获取数据并绘制图表或生成表格
fetch('/history_data')
    .then(response => response.json())
    .then(data => {
        if (!Array.isArray(data) || data.length === 0) {
            alert('暂无历史数据');
            return;
        }

        // 按时间排序
        data.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));

        const timestamps = data.map(d => d.timestamp);
        const temps = data.map(d => parseFloat(d.temp));
        const hums = data.map(d => parseFloat(d.humidity));
        const lights = data.map(d => parseInt(d.light));

        chartData = { timestamps, temps, hums, lights };

        drawChart('tempChart', '温度变化 (°C)', timestamps, temps, '#ff7300');
        drawChart('humChart', '湿度变化 (%)', timestamps, hums, '#339af0');
        drawChart('lightChart', '光照强度变化 (lux)', timestamps, lights, '#2fb344');

        generateTable(data);
    })
    .catch(error => {
        console.error('获取数据失败:', error);
        alert('获取历史数据失败，请刷新重试。');
    });

function drawChart(id, title, xAxisData, seriesData, color) {
    const chart = echarts.init(document.getElementById(id));
    chart.setOption({
        title: { text: title },
        tooltip: {
            trigger: 'axis',
            formatter: (params) => {
                return `${params[0].name}<br/>` +
                    `${params[0].seriesName}: ${params[0].value} ${params[0].unit}`;
            }
        },
        xAxis: {
            type: 'category',
            name: '时间',
            data: xAxisData,
            axisLabel: {
                rotate: 45,
                formatter: (value) => value.slice(11, 16)
            }
        },
        yAxis: {
            type: 'value',
            name: title.includes('温度') ? '°C' : title.includes('湿度') ? '%' : 'lux'
        },
        series: [{
            name: title.split(' ')[0],
            type: 'line',
            data: seriesData,
            smooth: true,
            itemStyle: { color: color },
            showSymbol: false
        }],
        dataZoom: [{ type: 'slider', start: 0, end: 100 }]
    });
}

// let chartData = null; // 存储获取到的数据，避免重复请求
// let tableLoaded = false; // 标记表格是否已加载过

function generateTable(data) {
    const tbody = document.querySelector('#data-table tbody');
    tbody.innerHTML = '';

    // ✅ 按时间升序排序（最早的时间排在最前面）
    data.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));

    data.forEach(item => {
        const row = document.createElement('tr');

        // 替换 ISO 时间格式中的 T 为 空格，并去掉毫秒部分
        const formattedTime = item.timestamp.replace("T", " ").split(".")[0];

        row.innerHTML = `
            <td>${formattedTime}</td>
            <td>${item.temp}</td>
            <td>${item.humidity}</td>
            <td>${item.light}</td>
        `;
        tbody.appendChild(row);
    });
}

// 控制图表和表格切换
function toggleView() {
    const chartView = document.getElementById('chart-view');
    const tableView = document.getElementById('table-view');
    const loader = document.getElementById('table-loader');

    if (chartView.style.display === 'none') {
        chartView.style.display = 'flex';
        tableView.style.display = 'none';
    } else {
        chartView.style.display = 'none';
        tableView.style.display = 'block';

        // 如果表格尚未加载，则加载一次
        if (!tableLoaded) {
            loader.style.display = 'block'; // 显示加载中提示

            fetch('/history_data')
                .then(res => res.json())
                .then(data => {
                    if (!Array.isArray(data) || data.length === 0) {
                        tbody.innerHTML = '<tr><td colspan="4">暂无数据</td></tr>';
                        return;
                    }

                    generateTable(data);
                    tableLoaded = true; // 标记表格已加载
                })
                .catch(error => {
                    console.error('获取数据失败:', error);
                    tbody.innerHTML = '<tr><td colspan="4">加载数据失败</td></tr>';
                })
                .finally(() => {
                    loader.style.display = 'none'; // 隐藏加载提示
                });
        }
    }
}
</script>

</body>
</html>